package com.copro.chemdb.stat.rule;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.result.Answer;
import com.copro.chemdb.result.AnswerListGetter;
import com.copro.chemdb.result.ResultUtils;
import com.copro.chemdb.stat.AbstractStatRule;
import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.subject.Subject;
import com.copro.chemdb.result.Result;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;

public class Rule3C1 extends AbstractStatRule {

	private AnswerListGetter getAnswers(Application app, Subject subject,
			int type) throws SimpleException {
		AnswerListGetter callback = new AnswerListGetter(
				new LinkedList<Answer>());
		SQLSegment sql = app.getSQL("rule3c1.getAnswers");
		sql.set("subjectId", subject.getId() <= 0 ? "NULL" : subject.getId());
		sql.set("type", type);
		app.query(sql.toString(), callback);
		return callback;
	}

	@Override
	public StatResult doStat(Application app, Subject subject, int statType)
			throws SimpleException {
		List<Answer> ans = getAnswers(app, subject, statType).getList();
		Map<Integer, Result> reSet = new HashMap<Integer, Result>();
		Map<Integer, List<Answer>> anSet = new HashMap<Integer, List<Answer>>();
		/* counting... */
		for (Iterator<Answer> it = ans.iterator(); it.hasNext();) {
			Answer an = it.next();
			int resultId = an.getResultId();
			Result re = reSet.get(resultId);
			if (null == re) {
				re = ResultUtils.getResult(app, resultId);
				if (re.getId() <= 0)
					continue;
				reSet.put(resultId, re);
				anSet.put(resultId, new LinkedList<Answer>());
			}
			List<Answer> list = anSet.get(resultId);
			list.add(an);
		}
		/* output as list */
		List<List<Object>> rows = new LinkedList<List<Object>>();
		for (Iterator<Result> it = reSet.values().iterator(); it.hasNext();) {
			Result result = it.next();
			List<Object> cells = new LinkedList<Object>();
			cells.add(result.getBrief());
			List<Answer> rans = anSet.get(result.getId());
			for (Iterator<Answer> anIt = rans.iterator(); anIt.hasNext();) {
				Answer an = anIt.next();
				cells.add(an.getStrValue());
			}
			rows.add(cells);
		}

		Hashtable<String, Object> result = new Hashtable<String, Object>();
		result.put("count", reSet.size());
		result.put("rows", rows);
		result.put("text", subject.getBrief());
		return new StatResult("rule3c1", result);
	}

	@Override
	public void setup(Properties conf) {

	}

}
